package com.iap.admin.view.code
{
	import com.iap.app.util.FormUtils;
	import com.iap.common.model.Image;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.events.ValidationResultEvent;
	import mx.validators.Validator;
	
	import org.osflash.signals.Signal;
	
	import spark.components.Group;
	
	public class EditViewCode extends Group
	{
		protected const STATE_NEW:String = "NEW";
		protected const STATE_EDIT:String = "EDIT";
		
		protected const FORM_PREFIX:String = "Form";

		[Bindable]
		protected var formIsValid:Boolean = false;

		[Bindable]
		protected var deleteEnabled:Boolean = false;

		protected var validateData:Array = new Array();
		
		protected var focussedFormControl:DisplayObject;

		public var onCancel:Signal = new Signal(String);
		public var onReady:Signal = new Signal(String);
		public var onImageComplete:Signal = new Signal(Image);

		public var model:Object;

		public function EditViewCode()
		{
			super();
		}

		protected function homeClick(evt:MouseEvent):void
		{
			onCancel.dispatch(evt.target.name);
		}

		protected function validateForm(event:Event = null):void 
		{              
			if(event!=null)
			{
				focussedFormControl = event.target as DisplayObject;
			}    
			formIsValid = true;
			for each(var validator:Validator in validateData)
			{
				if(validator.enabled)
					validate(validator);
			}
		}
		
		protected function validate(validator:Validator):Boolean
		{                
			var validatorSource:DisplayObject = validator.source as DisplayObject;
			var suppressEvents:Boolean = (validatorSource != focussedFormControl);
			var event:ValidationResultEvent = validator.validate(null, suppressEvents); 
			var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);
			formIsValid = formIsValid && currentControlIsValid;
			return currentControlIsValid;
		}
		
		private function setErrorMessage(source:Object, message:String):void
		{
			const errorName:String = "errorString";
			if(source.hasOwnProperty(errorName))
			{
				source[errorName] = message;
			}
		}

		public function fill(model:Object):void
		{
			if(model == null) return;
			this.model = model;
			FormUtils.fillFormControl(this, model, FORM_PREFIX);
			validateForm();
			deleteEnabled = true;
		}
	}
}